package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-11
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        // 校验参数
        if (dto == null ||
                (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getEquipmentId()))
        ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 如果手机号和密码不为空,使用手机号和密码登录
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            // 正常验证生成token
            // 根据手机号查找数据
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(query);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 获取用户的盐
            // 使用用户传入的密码+salt进行MD5加密,与数据库中的密码对比
            String pwd = dto.getPassword() + one.getSalt();
            String ps = DigestUtils.md5DigestAsHex(pwd.getBytes());
            if (ps.equals(one.getPassword())) {
                // 对比成功,使用JWT生成token
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("userId", one.getId());
                String token = AppJwtUtil.getToken(userMap);
                Map<String, Object> map = new HashMap<>();
                map.put("token", token);
                return ResponseResult.okResult(map);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }

        // 如果设备id不为空,使用0生成token
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("userId", 0);
            String token = AppJwtUtil.getToken(userMap);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        return null;
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService followService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 当前登录的用户可以从本地线程中查询
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建关注对象
        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setUserId(user.getUserId());
        ApUser apUser = this.getById(user.getUserId());
        userFollow.setUserName(apUser.getName());

        // 关注的用户可以通过作者去查询
        ApAuthor apAuthor = null;
        ResponseResult<ApAuthor> responseResult = articleFeign.getAuthorById(dto.getAuthorId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            apAuthor = responseResult.getData();
        }
        if (apAuthor != null) {
            userFollow.setFollowId(apAuthor.getUserId());
            userFollow.setFollowName(apAuthor.getName());
        }
        userFollow.setLevel(0);
        userFollow.setCreatedTime(new Date());
        LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
        query.eq(ApUserFollow::getUserId, user.getUserId());
        query.eq(ApUserFollow::getFollowId, apAuthor.getUserId());
        // 判断操作是关注还是取消关注
        if (dto.getOperation() == 0) {
            // 如果是关注,需要保存记录,判断该用户是否已经对这个作者有过关注记录
            ApUserFollow one = followService.getOne(query);
            if (one == null) {
                followService.save(userFollow);
            }
        } else {
            // 否则,删除记录
            followService.remove(query);
        }
        // 同步数据到行为微服务
        FollowBehaviorDto behaviorDto = new FollowBehaviorDto();
        behaviorDto.setUserId(user.getUserId());
        behaviorDto.setFollowId(apAuthor.getUserId());
        behaviorDto.setOperation(dto.getOperation());
        behaviorDto.setEquipmentId(dto.getEquipmentId());
        String json = JSON.toJSONString(behaviorDto);
        kafkaTemplate.send(followBehaviorTopic, json);
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
}
